<template>
  <h1>员工列表练习</h1>
  <input type="text" placeholder="请输入员工姓名" v-model="emp.name">
  <input type="text" placeholder="请输入员工工资" v-model="emp.salary">
  <input type="text" placeholder="请输入员工岗位" v-model="emp.job">
  <button @click="addEmp">点我添加员工</button>
  <hr>
  <table border="1">
    <tr>
      <th>员工编号</th>
      <th>员工姓名</th>
      <th>员工工资</th>
      <th>员工岗位</th>
      <th>删除</th>
    </tr>
    <tr v-for="(e,index) in arr">
      <td>{{index+1}}</td>
      <td>{{e.name}}</td>
      <td>{{e.salary}}</td>
      <td>{{e.job}}</td>
      <td><button @click="del(index)">删除</button></td>
    </tr>
  </table>

</template>

<script setup>
import {ref} from "vue";

//定义对象用来保存员工数据
const emp = ref({name:'',salary:'',job:''});
//定义数组用来保存多个员工对象
const arr = ref([]);
//定义添加员工的方法
const addEmp = ()=>{
  if(emp.value.name.trim()=='' || emp.value.salary.trim()=='' || emp.value.job.trim()==''){
    alert('请输入完整的员工信息!');
    return;
  }
  //将双向绑定收集到的员工数据添加到数组中
  arr.value.push(emp.value);
  //将添加成功后的数据清空,否则输入框以为是在修改同一个数据,而不是添加新值
  emp.value = {name:'',salary:'',job:''};
}
const del = (index) => {
  if(confirm('确定删除该员工吗？')){
    arr.value.splice(index,1);
  }
}
</script>

<style scoped>

</style>